<!--
 * @Description: 采购申请
 * @Author: wangwangwang
 * @Date: 2020-09-21 14:09:06
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-12-29 14:52:27
-->
<template>
  <div class="pages_content table">
    <el-container>
      <el-header>
        <breaDcrumb />
      </el-header>
      <el-main style="display:flex">
        <div>
          <div class="header_right" @click="showCardNav = !showCardNav">
            <div class="title">搜索</div>
            <div>
              <transition name="from"></transition>
              <span v-show="!showCardNav">
                <i style="margin-right: 5px;" class="el-icon-arrow-down"></i>
              </span>
              <transition name="to"></transition>
              <span v-show="showCardNav">
                <i style="margin-right: 5px;" class="el-icon-arrow-up"></i>
              </span>
            </div>
          </div>
          <div v-show="showCardNav" class="hr"></div>
          <el-collapse-transition>
            <div v-show="showCardNav">
              <div class="search">
                <span style="margin-bottom:10px;display: inline-block;">
                  <span style="margin-right: 12px;">生成日期</span>
                  <el-date-picker v-model="tableParam.needTimes" value-format="yyyy-MM-dd" type="date" placeholder="选择日期时间"></el-date-picker>
                </span>
                <span style="margin-left: 24px;">
                  <span style="margin-right: 12px;">需求日期</span>
                  <el-date-picker v-model="tableParam.needDate" value-format="yyyy-MM-dd" type="date" placeholder="选择日期时间"></el-date-picker>
                </span>
                <span style="margin-left: 24px;">
                  <span style="margin-right: 12px;">站点名称</span>
                  <el-select ref="selection2" v-model="tableParam.station" filterable clearable placeholder="请选择">
                    <el-option v-for="(item, index) in stationIdlist" :key="index" :label="item.name" :value="item.name"></el-option>
                  </el-select>
                </span>
                <span style="margin-left: 24px;">
                  <span style="margin-right: 12px;">原物料名称</span>
                  <el-select v-model="tableParam.materials" placeholder="请选择" filterable clearable>
                    <el-option v-for="item in materialsIdlist" :key="item.id" :label="item.itemName" :value="item.itemName"></el-option>
                  </el-select>
                </span>
                <el-button icon="el-icon-search" size="medium" class="bottom_all but1" @click="(tableParam.page = 1), gettableData()">查 询</el-button>
                <el-button size="medium" class="bottom_all_two" style="margin-left:12px;" @click="init()">重 置</el-button>
              </div>
            </div>
          </el-collapse-transition>
          <div class="hr"></div>
          <div class="card">
            <div class="card_nav">
              <div>
                <div>
                  <el-button size="small" class="bottom_all" style="margin-left: 0;" @click="addFromDate('添加'),list=[],disabledType=false">
                    <i class="icon iconfont iconicon_button_add" style="font-size: 12px;"></i>
                    添加
                  </el-button>
                </div>
              </div>
              <div>
                <el-dropdown :hide-on-click="false" trigger="click" style="margin: 0 20px;">
                  <el-link :underline="false">
                    <span class="el-icon--left">
                      <i class="iconfont iconicon_button_filtrate"></i>
                    </span>
                    筛选
                  </el-link>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item v-for="(item, index) in table" :key="index">
                      <el-checkbox v-model="item.status">{{ item.label }}</el-checkbox>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
            </div>
            <div v-loading="tableLoading" class="card_info" :style="style">
              <el-table :header-cell-style="{ background: '#f3f6f9' }" :cell-style="{ borderRight: 'none' }" border stripe style="width:100%" :data="tableData" tooltip-effect="dark">
                <template v-for="(item, index2) in table">
                  <el-table-column v-if="item.status" :key="index2" :label="item.label" align="center" :width="item.width" :fixed="(item.label =='操作')?'right':false">
                    <template slot-scope="scope">
                      <el-link v-if="item.label == '供应详情'" class="table_link" :underline="false" @click="showdetails1(scope.row)">供应详情</el-link>
                      <div v-else-if="item.label == '状态'">
                        <span v-if="scope.row.planStatus == 1">待申请</span>
                        <span v-if="scope.row.planStatus == 2">待审批</span>
                        <span v-if="scope.row.planStatus == 3">已通过</span>
                        <span v-if="scope.row.planStatus == 4">已拒绝</span>
                      </div>
                      <div v-else-if="item.label == '操作'">
                        <el-link v-if="scope.row.planStatus == 1&&ButtonList.findIndex(res=>(res.buttonValue=='SHENQ'))!==-1" class="table_link" :underline="false" @click="addFromDate('添加'),setFormData(scope.row,'','', '申请')">申请</el-link>
                        <el-link v-if="scope.row.planStatus == 4" class="table_link" :underline="false" @click="remarkFun(scope.row.remark)">驳回原因</el-link>
                        <span v-if="scope.row.planStatus == 4">
                          <el-link v-if="ButtonList.findIndex(res=>(res.buttonValue=='XIUGAI'))!==-1" class="table_link" :underline="false" @click="addFromDate('修改'),setFormData(scope.row,true)">修改</el-link>
                        </span>
                        <el-link v-if="scope.row.planStatus>1" class="table_link" :underline="false" @click="addFromDate('查看'),setFormData(scope.row,true,true)">查看</el-link>
                      </div>
                      <span v-else>{{ scope.row[item.prop] }}</span>
                    </template>
                  </el-table-column>
                </template>
              </el-table>
            </div>
          </div>
        </div>
      </el-main>
      <div class="card_bottom">
        <div class="card_bottom_left">
          <div class="top_page_totle">总共{{ total }}条</div>
          <el-pagination :current-page.sync="tableParam.page" :page-size="tableParam.pageSize" :page-sizes="[10, 20, 30, 40,50,100,200,500,1000]" layout="prev,pager,sizes,next,jumper" :total="total" @size-change="sizeChange" @current-change="gettableData()"></el-pagination>
        </div>
        <div>
          <el-button size="mini" icon="el-icon-refresh-right" class="bottom_all_two" @click="gettableData">刷新</el-button>
        </div>
      </div>
    </el-container>
    <!-- 添加 -->
    <el-dialog v-dialogDrag :visible.sync="addDialog" width="1200px" :close-on-click-modal="false">
      <span slot="title" class="dialog-title">{{ addDialogTitle }}</span>
      <div>
        <el-form ref="reffromDate" :rules="rules" :inline="true" :model="fromDate" label-width="100px" :hide-required-asterisk="true" :disabled="disabledType">
          <el-form-item v-if="UserInfo.adminStatus == 1" prop="companyId">
            <span slot="label" style="color:#FF0000;">公司</span>
            <el-select ref="selection1" v-model="fromDate.companyId" placeholder="请选择" @change="setstationIdlist,$nextTick(()=>{fromDate.companyName = $refs.selection1.selectedLabel})">
              <el-option v-for="(item, index) in companyIdlist" :key="index" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="stationId">
            <span slot="label" style="color:#FF0000;">站点</span>
            <el-select ref="selection2" v-model="fromDate.stationId" placeholder="请选择" :disabled="stationIdlist.length==0" @change="setlist(),get_simple_organizationFun(fromDate.stationId),$nextTick(()=>{fromDate.station = $refs.selection2.selectedLabel}),inventoryFun()">
              <el-option v-for="(item, index) in stationIdlist" :key="index" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="materialsId">
            <span slot="label" style="color:#FF0000;">原物料名称</span>
            <el-select v-model="fromDate.materialsId" filterable placeholder="请选择" @change="setlist(),inventoryFun()">
              <el-option v-for="(item, index) in materialsIdlist" :key="index" :label="item.itemName" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="specificationId">
            <span slot="label" style="color:#FF0000;">规格</span>
            <el-select v-model="fromDate.specificationId" filterable placeholder="请选择">
              <el-option v-for="(item, index) in speList" :key="index" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="需求时间">
            <el-date-picker v-model="fromDate.needTime" default-time="06:00:00" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期时间"></el-date-picker>
          </el-form-item>
          <el-form-item label="理论需求总量">
            <el-input v-model="fromDate.theoryNumber" onkeypress='return( /\d|\./.test(String.fromCharCode(event.keyCode)))' @input="fromDate.theoryNumber=$regExp.checkNum(fromDate.theoryNumber)" @blur="fromDate.theoryNumber=$regExp.blurCheckNum(fromDate.theoryNumber)"></el-input>
          </el-form-item>
          <el-form-item label="库存缺口量">
            <div style="width: 240px;">{{fromDate.inventory}}</div>
          </el-form-item>
          <el-form-item prop="practiceNumer">
            <span slot="label" style="color:#FF0000;">实际需求量</span>
            <el-input v-model="fromDate.practiceNumer" onkeypress='return( /\d|\./.test(String.fromCharCode(event.keyCode)))' @input="fromDate.practiceNumer=$regExp.checkNum(fromDate.practiceNumer)" @blur="fromDate.practiceNumer=$regExp.blurCheckNum(fromDate.practiceNumer)"></el-input>
          </el-form-item>
        </el-form>
        <div>
          <span class="dialog-title">原物料供应详情</span>
          <el-button v-if="disabledType==false" size="mini" class="bottom_three" style="margin-left:40px;" @click="getplanlist()">获取计划</el-button>
          <el-button v-if="disabledType==false" size="mini" class="bottom_all" style="margin-left: 12px;" @click="addItem()">
            <i class="icon iconfont iconicon_button_add" style="font-size: 12px;"></i>
            添加
          </el-button>
        </div>
        <div style="padding-top:10px">
          <el-table v-loading="loading" :header-cell-style="{ background: '#f3f6f9' }" :cell-style="{ borderRight: 'none' }" border stripe style="width:100%" :data="fromDate.list" tooltip-effect="dark">
            <el-table-column label="合同编号" align="center">
              <template slot-scope="scope">
                <span v-if="disabledType">{{scope.row.contractNo}}</span>
                <el-select v-else v-model="scope.row.contractId" placeholder="请选择" style="width:100%" @change="changeitem(scope.row)">
                  <el-option v-for="(item, index) in list" :key="index" :label="item.contractNo+'：'+item.supplier" :value="item.contractId"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="原物料供应商" align="center" prop="supplierName"></el-table-column>
            <el-table-column label="合同签订主体" align="center" prop="contractSigningSubject"></el-table-column>
            <el-table-column label="原物料" align="center">
              <template slot-scope="scope">
                <span v-if="disabledType">{{scope.row.rawName}}</span>
                <el-select v-else v-model="scope.row.rawMaterialsId" :disabled="disabledType" placeholder="请选择" style="width:100%" @change="change1(scope.row)">
                  <el-option v-for="(item, index) in scope.row.list" :key="index" :label="item.productName+'_'+item.specification+'_'+item.brand" :value="item.productId"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="规格" align="center" prop="specification"></el-table-column>
            <el-table-column label="品牌" align="center" prop="brand"></el-table-column>
            <el-table-column label="份额" align="center" prop="supplierPercent">
              <template slot-scope="scope">
                <span v-if='!scope.row.supplierPercent'>/</span>
                <span v-else>{{scope.row.supplierPercent+'%'}}</span>
              </template>
            </el-table-column>
            <el-table-column label="是否含运输" align="center">
              <template slot-scope="scope">
                <span v-if="scope.row.transportStatus==1" style="color:#00A754;">是</span>
                <span v-else style="color:#969799;">否</span>
              </template>
            </el-table-column>
            <el-table-column label="需求量" align="center">
              <template slot-scope="scope">
                <span v-if=" disabledType">{{scope.row.planNumber}}</span>
                <el-input-number v-else v-model="scope.row.planNumber" :disabled="disabledType" style="width:100%" :controls="false" :precision="0"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="采购量" align="center">
              <template slot-scope="scope">
                <span>{{scope.row.supplierNumber}}</span>
              </template>
            </el-table-column>
            <el-table-column label="车辆外包合同" align="center" prop="carContractNo" width="200px">
              <template slot-scope="scope">
                <span v-if=" disabledType">{{scope.row.carContractNo}}</span>
                <span v-else>
                  <span v-if="scope.row.transportStatus==1">{{scope.row.carContractNo}}</span>
                  <span v-else>
                    <el-select v-model="scope.row.carContractId" placeholder="请选择" style="width:100%" :disabled="scope.row.contractId && scope.row.rawMaterialsId && disabledType == false?false:true" @change="change2(scope.row)">
                      <el-option v-for="(item, index) in scope.row.planData1" :key="index" :label="item.contractNumber+'：'+item.supplierName" :value="item.contractId"></el-option>
                    </el-select>
                  </span>
                </span>
              </template>
            </el-table-column>
            <el-table-column label="车辆供应商" align="center" prop="carCompanyName"></el-table-column>
            <el-table-column v-if="disabledType==false" label="操作" align="left" width="120">
              <template slot-scope="scope">
                <el-button size="mini" class="bottom_two" @click="deleteItem(scope.$index)">
                  <i class="icon iconfont iconicon_button_delete" style="font-size: 12px;"></i>
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="bottom_all_two" @click="addDialog = false">取 消</el-button>
        <el-button v-show="!disabledType" class="bottom_all" style="margin-left: 24px;" @click="pagessubmitFromDate()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 查看详情 -->
    <el-dialog v-dialogDrag :visible.sync="detailsDialog" width="1015px" :close-on-click-modal="false">
      <span slot="title" class="dialog-title">查看详情</span>
      <div class="dialoginfo">
        <el-table :header-cell-style="{ background: '#f3f6f9' }" :cell-style="{ borderRight: 'none' }" border stripe style="width:100%" :data="list" tooltip-effect="dark">
          <el-table-column label="原物料合同编号" align="center" prop="contractNo"></el-table-column>
          <el-table-column label="原物料供应商" align="center" prop="supplierName"></el-table-column>
          <el-table-column label="原物料" align="center" prop="rawName"></el-table-column>
          <el-table-column label="规格" align="center" prop="specification"></el-table-column>
          <el-table-column label="品牌" align="center" prop="brand"></el-table-column>
          <el-table-column label="份额" align="center" prop="supplierPercent">
            <template slot-scope="scope">
              <span v-if='!scope.row.supplierPercent'>/</span>
              <span v-else>{{scope.row.supplierPercent+'%'}}</span>
            </template>
          </el-table-column>
          <el-table-column label="供应量" align="center" prop="supplierNumber"></el-table-column>
          <el-table-column label="是否含运输" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.transportStatus==0" style="color:#969799;">否</span>
              <span v-else style="color:#00A754;">是</span>
            </template>
          </el-table-column>
          <el-table-column label="车辆租赁合同编号" align="center" prop="carContractNo"></el-table-column>
          <el-table-column label="车辆租赁供应商" align="center" prop="carCompanyName"></el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="bottom_all_two" @click="detailsDialog=false">关 闭</el-button>
      </span>
    </el-dialog>
    <!-- 查看详情 -->
    <el-dialog v-dialogDrag :visible.sync="bhType" width="700px" :close-on-click-modal="false">
      <span slot="title" class="dialog-title">驳回原因</span>
      <div class="dialoginfo">
        {{bhTypeValue}}
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="bottom_all_two" @click="bhType=false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import mixin from "@/mixins/ICPSmixin.js";
import {
  queryPage,
  saveOrUpdate,
  Download,
  getPlanDetailById,
  getLotAllotsByStation,
  getContractCarByCondition,
  inventoryget_gap,
  getisByContractId
} from "@/api/smart/schedul/h.js";
import { getContracts } from "@/api/GHnumber/share.js";
import { getUserInfo } from "@/utils/auth.js";
import { getcompany, getUserAutList, get_simple_organization, getDicType } from "@/api/common.js";
import { get_station_list } from "@/api/smart/stocksake.js";

export default {
  mixins: [mixin],
  data() {
    return {
      disabledType: false,
      UserInfo: '',
      /*表格增删改查及下载接口*/
      queryPage: queryPage,
      DownloadURL: Download,
      /*表格数据*/
      table: [
        {
          label: "日供应计划ID",
          width: "200",
          prop: "id",
          status: true,
        },
        { label: "公司", prop: "companyName", status: true, width: '200' },
        { label: "站点名称", width: "auto", prop: "station", status: true },
        {
          label: "原物料名称",
          prop: "materials",
          status: true,
        },
        {
          label: "理论需求量",
          width: "auto",
          prop: "theoryNumber",
          status: true,
        },
        { label: "库存缺口量", width: "120", prop: "inventory", status: true },
        {
          label: "实际需求量",
          width: "auto",
          prop: "practiceNumer",
          status: true,
        },
        { label: "供应详情", width: "120", prop: "id", status: true },
        { label: "生成日期", width: "165", prop: "createTime", status: true, },
        { label: "需求日期", width: "165", prop: "needDate", status: true },
        { label: "状态", width: "auto", prop: "planStatus", status: true },
        { label: "操作", width: "auto", prop: "id", status: true, },
      ],
      pagesType: 0,
      /*添加表单数据*/
      rules: {
        stationId: [{required: true, message: '请选择站点'}],
        materialsId: [{required: true, message: '请选择原物料'}],
        specificationId: [{required: true, message: '请选择规格'}],
        practiceNumer: [{required: true, message: '请输入实际需求量'}]
      },
      stationIdlist: [],
      materialsIdlist: [],
      fromDate: {
        stationId: "",
        companyId: "",
        theoryNumber: '',
        practiceNumer: "",
        needTime: "",
        needDate: '',
        materialsId: "",
        dataType: 1,
        list: [],
        specificationId: ''
      },
      list: [],
      detailsDialog: false,
      listArr: [],
      bhType: false,
      bhTypeValue: '',
      loading: false,
      speList: [],
    };
  },
  async created() {
    this.UserInfo = await getUserInfo();
    if (this.UserInfo.adminStatus == 1) {
      /**通过typeId为公司类型id查询所有公司 */
      getcompany({ typeId: "19da56b9e85648059e3cf1e7da497da4" }).then((res) => {
        this.companyIdlist = res.data;
      });
    } else {
      this.stationIdlist = await getUserAutList(true)
    }
    /*存储拷贝的原初始化fromDate数据*/
    this.gettableData();
    getDicType({ code: "MATname" }).then((res) => {
      this.materialsIdlist = res.data.items;
    });
  },
  methods: {
    /**查询 库存缺口量*/
    inventoryFun() {
      if (this.fromDate.stationId && this.fromDate.materialsId) {
        inventoryget_gap({ stationId: this.fromDate.stationId, rawId: this.fromDate.materialsId }).then((res) => {
          this.fromDate.inventory = res.data.inventory
          this.$forceUpdate()
        })
      }
    },
    /**查询当前原物料合同的车辆外包合同 */
    getplanData1(row) {
      getContractCarByCondition({ contractId: row.contractId, rawId: row.rawMaterialsId, stationId: this.fromDate.stationId }).then((res) => {
        if (res.data?.length > 0) {
          row.planData1 = res.data;
          const carContract = this.formatTime(res.data);
          row.carContractId = carContract.contractId;
          row.carContractNo = carContract.contractNumber;
          row.carCompanyId = carContract.supplierId;
          row.carCompanyName = carContract.supplierName;
          this.$forceUpdate()
        } else if (res.codeMsg === '1') {
          this.$message({
            message: "车辆外包合同已过期！",
            type: "warning",
          });
          row.planData1 = []
        } else if (res.codeMsg === '0') {
          this.$message({
            message: "车辆外包合同空！",
            type: "warning",
          });
          row.planData1 = []
        }
      })
    },
    /**
     * @Description: 传数组找数组中最新的数据
     * @param {*}
     * @Author: wangwangwang
     */    
    formatTime (data) {
      return data.reduce((total, current) => (
        new Date(current.contractCreateTime).getTime() > new Date(total.contractCreateTime).getTime() ? current : total
      ));
    },
    /**通过站点查询公司 */
    get_simple_organizationFun(id) {
      get_simple_organization({ id: id }).then((res) => {
        this.fromDate.companyId = res.data.id
        this.fromDate.companyName = res.data.name
      });//查询站点所属公司
    },
    setFormData(d, type, type2, type3) {
      this.fromDate = d;
      if(type3 && type3 === '申请') {
        this.$nextTick(()=>{
          // 获取第二天早上6点的时间戳
          const time = new Date(new Date().setHours(0, 0, 0, 0)) / 1000 + 60*60*30;
          const d = new Date(time * 1000);
          this.fromDate.needTime = (d.getFullYear()) + "-" + 
                                  (d.getMonth() + 1) + "-" +
                                  (d.getDate()) + " " + 
                                  (d.getHours() < 10 ? '0' + d.getHours() : d.getHours()) + ":" + 
                                  (d.getMinutes() < 10 ? '0' + d.getMinutes() : d.getMinutes()) + ":" + 
                                  (d.getSeconds() < 10 ? '0' + d.getSeconds() : d.getSeconds());    
        })  
      }
      if (!type) {
        this.fromDate.list = [];
        this.fromDate.needTime = ""; //需求时间
      }
      this.disabledType = false
      if (type2) {
        this.disabledType = true
      }
      /**
       * @Description: 通过站点和原物料获取合同号
       * @Param: 
       * @Author: wangwangwang
       */
      const params = {
        id: this.fromDate.materialsId,
        stations: this.fromDate.stationId,
      }
      this.loading = true;
      getContracts(params).then(res => {
        if (res.code === 1001) {
          this.fromDate.specificationId = '';
          this.$refs.reffromDate.clearValidate();
          this.speList = [];
          res.data.forEach(item=>{
            item.list.forEach(sItem=>{
              this.speList.push(JSON.stringify({value: sItem.specificationId, label: sItem.specification}))
            })
          })
          this.speList = [...new Set(this.speList)];
          for(let i = 0; i < this.speList.length; i++) {
            this.speList[i] = JSON.parse(this.speList[i])
          }
          if (!res.data.length) {
            this.$message.warning('该物料在本站点下无合同');
            return;
          }
          this.list = res.data;
          this.showdetails(d);
          return
        }
        this.loading = false;
      })
    },
    /*重置数据*/
    init() {
      this.tableParam.needTimes = "";
      this.tableParam.needDate = "";
      this.tableParam.station = "";
      this.tableParam.materials = "";
      this.gettableData();
    },
    /*添加*/
    addItem() {
      let item = {
        contractId: "",
        contractNo: "",
        supplierId: "",
        supplierName: "",
        rawId: "",
        rawName: "",
        supplierPercent: "",
        transportStatus: null,
        supplierNumber: "",
        carContractId: "",
        carContractNo: "",
        carCompanyId: "",
        carCompanyName: "",
        specification: "",
        brand: "",
      };
      this.fromDate.list.push(item);
      this.$forceUpdate();
    },
    deleteItem(index) {
      this.fromDate.list.splice(index, 1);
    },
    /*保存*/
    pagessubmitFromDate() {
      let _this = this;
      let fromDate = JSON.parse(JSON.stringify(_this.fromDate))
      _this.$refs.reffromDate.validate((valid) => {
        if (valid) {
          if (fromDate.list.length == 0) {
            _this.$message({
              message: "警告哦，请至少添加一条计划",
              type: "warning",
            });
            return;
          }
          if (!fromDate.needTime) {
            _this.$message({
              message: "请选择需求日期",
              type: "warning",
            });
            return;
          }
          const judge = fromDate.list.every((v) => {
            if (v.transportStatus == 1) {
              if (v.contractId && v.rawMaterialsId && v.supplierId) {
                return true
              } else {
                return false
              }
            } else {
              if (v.contractId && v.rawMaterialsId && v.carContractNo && v.supplierId) {
                return true
              } else {
                return false
              }
            }
          })
          if (!judge) {
            _this.$message({
              message: "请检查表格数据是否填写完整！",
              type: "warning",
            });
            return
          }
          /**
           * @Description: 合同编号和原物料必须唯一
           * @param {*}
           * @Author: wangwangwang
           */
          if ([...new Set(fromDate.list.map((item) => item.contractId+item.rawMaterialsId))].length < fromDate.list.length) {
            this.$message.warning('合同编号和原物料不能相同');
            return;
          }
          let sizeNumber = 0
          fromDate.list.forEach((v) => {
            sizeNumber = sizeNumber + Number(v.supplierNumber)
          })
          if (sizeNumber > fromDate.practiceNumer) {
            _this.$message({
              message: "警告哦，采购申请供应量不能大于实际需求量!",
              type: "warning",
            });
            return;
          }
          fromDate.materials = _this.$fromatTable(
            _this.materialsIdlist,
            _this.fromDate.materialsId,
            "id",
            "itemName"
          );
          // 对比组装
          let alldata = fromDate.list.filter((res) =>
            this.listArr.some((item) => res.id == item.id)
          );
          alldata.forEach((res) => {
            res.type = 2; //2是修改
          });
          let deleteData = this.listArr.filter(
            (res) => !alldata.some((item) => res.id == item.id)
          );
          deleteData.forEach((res) => {
            res.type = 0; //0是删除
          });
          let addData = fromDate.list.filter(
            //新增的type默认写死为 1
            (res) => !alldata.some((item) => res.id == item.id)
          );
          fromDate.list = [...alldata, ...deleteData, ...addData];
          // 对比组装
          fromDate.planStatus = 2;
          let datalist = fromDate.list.map(res => ({ id: res.contractId, supplierName: res.supplierName }));
          fromDate.needDate = fromDate.needTime;
          fromDate.operation = 1;
          if (_this.addDialogTitle !== '添加') {
            _this.$confirm("确定再次提交审批?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              cancelButtonClass: "bottom_all_two",
              confirmButtonClass: "bottom_all",
              type: "warning",
            }).then(() => {
              getisByContractId(datalist).then(res => {
                if (res.code === 1001) {
                  if (res.data != '') {
                    _this.$message({
                      showClose: true,
                      message: '采购申请-添加：供应商未分配账号！',
                      type: 'warning',
                      duration: 5000
                    });
                  }
                }
              })
              saveOrUpdate({ ...fromDate }).then(res => {
                if (res.code === 1001) {
                  _this.$message.success('添加成功');
                  _this.gettableData();
                  _this.addDialog = false;
                }
              })
            })
            return
          }
          getisByContractId(datalist).then(res => {
            if (res.code === 1001) {
              if (res.data != '') {
                _this.$message({
                  showClose: true,
                  message: '采购申请-添加：供应商未分配账号！',
                  type: 'warning',
                  duration: 5000
                });
              }
            }
          })
          saveOrUpdate({ ...fromDate }).then(res => {
            if (res.code === 1001) {
              _this.$message.success('添加成功');
              _this.gettableData();
              _this.addDialog = false;
            }
          })
        }
      });
    },
    /*查看详情*/
    showdetails1(low) {
      getPlanDetailById({ planId: low.id }).then((res) => {
        if (res.code === 1001) {
          this.list = res.data;
          this.detailsDialog = true;
        }
      });
    },
    /*查看详情*/
    showdetails(low) {
      getPlanDetailById({ planId: low.id }).then((res) => {
        if (res.code === 1001) {
          for (let i = 0; i < res.data.length; i+=1) {
            getContractCarByCondition({ contractId: res.data[i].contractId, rawId: res.data[i].rawId, stationId: this.fromDate.stationId }).then((resq) => {
              if (resq.data?.length > 0) {
                res.data[i].planData1 = resq.data;
              }
              if (i === res.data.length - 1) {
                setTimeout(() => {
                  this.initData(res.data);
                }, 500)
              }
            });
          }
          if (!res.data.length) this.loading = false;
        }
      });
    },
    initData (data) {
      const newData = data.map(item => {
        for (let i = 0; i < this.list.length; i+=1) {
          if (this.list[i].contractNo === item.contractNo) {
            return {...item, list: this.list[i].list, rawMaterialsId: item.rawId}
          }
        }
      })
      this.fromDate.list = newData;
      this.listArr = this.copy(data);
      this.loading = false;
      this.$forceUpdate();
    },
    /*根据公司获取站点，站点原物料变化时置空*/
    setstationIdlist() {
      get_station_list({ parentId: this.fromDate.companyId }).then((res) => {
        this.stationIdlist = res.data;
      });
      this.fromDate.stationId = "";
      this.fromDate.list = [];
      this.list = [];
    },
    setlist() {
      /**
      * @Description: 设置默认值
      * @Param: 
      * @Author: wangwangwang
      */
      if (!this.fromDate.stationId) return
      if (!this.fromDate.materialsId) return
      /**
       * @Description: 通过站点和原物料获取合同号
       * @Param: 
       * @Author: wangwangwang
       */
      const params = {
        id: this.fromDate.materialsId,
        stations: this.fromDate.stationId,
      }
      getContracts(params).then(res => {
        if (res.code === 1001) {
          this.fromDate.specificationId = '';
          this.$refs.reffromDate.clearValidate();
          this.speList = [];
          res.data.forEach(item=>{
            item.list.forEach(sItem=>{
              this.speList.push(JSON.stringify({value: sItem.specificationId, label: sItem.specification}))
            })
          })
          this.speList = [...new Set(this.speList)];
          for(let i = 0; i < this.speList.length; i++) {
            this.speList[i] = JSON.parse(this.speList[i])
          }
          this.fromDate.list = []
          this.list = res.data;
          if (!res.data.length) {
            this.$message.warning('该物料在本站点下无合同');
            return;
          }
        }
      })
    },
    /*获取计划*/
    getplanlist() {
      if (!this.fromDate.stationId) {
        this.$refs.reffromDate.validateField("stationId");
        return;
      }
      if (!this.fromDate.materialsId) {
        this.$refs.reffromDate.validateField("materialsId");
        return;
      }
      if (!this.fromDate.specificationId) {
        this.$refs.reffromDate.validateField("specificationId");
        return;
      }
      if (!this.fromDate.practiceNumer) {
        this.$refs.reffromDate.validateField("practiceNumer");
        return;
      }
      getLotAllotsByStation({
        stationId: this.fromDate.stationId,
        rawId: this.fromDate.materialsId,
      }).then((res) => {
        if (res.code === 1001) {
          const newData = res.data.map(item => ({ ...item, supplierName: item.supplier, supplierPercent: item.lotNum, transportStatus: item.isCarriage, planNumber: this.fromDate.practiceNumer * item.lotNum * 0.01, rawName: item.rawMaterialsName, id: '', rawNameId: item.rawMaterialsId, }));
          console.log(newData)
          // newData.map(item => {
          //   item.list = item.list.filter(sp => {
          //     return sp.specificationId === this.fromDate.specificationId
          //   })
          // })
          this.fromDate.list = newData;
          let supplierPercent = 0;
          this.fromDate.list.forEach(item=>{
            supplierPercent+=item.supplierPercent;
          })
          const a = 100 / supplierPercent;
          this.fromDate.list.forEach(item=>{
            item.planNumber = (item.planNumber * a).toFixed(2);
          })
          this.fromDate.list.forEach((v) => {
            this.changeitem(v, true)
          })
          // // 设置默认选项，如果没有，就删除
          // let sp
          // this.fromDate.list.map(item => {
          //   sp = item.list.filter(spItem => {
          //     return sItem
          //   })
          // })
          this.fromDate.list.forEach((item) => {
            if (item.transportStatus != 1) {
              this.getplanData1(item)
            }
          });
          this.$forceUpdate()
        }
      });
    },
    /*拉取数据*/
    changeitem(item, type) {
      let data = this.list.find((res) => res.contractId == item.contractId);

      // 设置默认规格选择
      item.list = data.list;
      let sp = data.list.filter(spItem => {
        return spItem.specificationId === this.fromDate.specificationId
      })
      if (sp.length) {
        item.rawMaterialsId = sp[0].productId
        this.change1(item)
      }
      if (type) {   // 初始化列表，退出
        return
      }
      item.contractNo = data.contractNo;
      item.companyId = data.companyId;
      item.company = data.company;
      item.supplierId = data.supplierId;
      item.supplierName = data.supplier;
      item.transportStatus = data.isCarriage;
      item.rawMaterialsId = '';
      item.specification = '';
      item.brand = '';
      item.carContractNo = '';
      item.carCompanyId = '';
      item.carCompanyName = '';
      item.supplierNumber = '';
      item.planData2 = []
      item.carContractId = '';
    },
    change1(item) {
      let data = item.list.find(
        (res) => res.productId == item.rawMaterialsId
      );
      item.rawId = data.productId;
      item.rawName = data.productName;
      item.brand = data.brand;
      item.specification = data.specification;
      item.carContractId = '';
      item.carContractNo = '';
      item.carCompanyId = '';
      item.carCompanyName = '';
      /**
       * @Description: 切换了原物料，如果当前数据是不包运输则获取最新的车辆外包合同
       * @param {*}
       * @Author: wangwangwang
       */      
      if (item.transportStatus != 1) {
        this.getplanData1(item);
      }
    },
    change2(item) {
      let data = item.planData1.find((res) => res.contractId == item.carContractId);
      item.carContractNo = data.contractNumber;
      item.carCompanyId = data.supplierId;
      item.carCompanyName = data.supplierName;
    },
    remarkFun(val) {
      this.bhType = true
      if (val == '') {
        val = '未填写。'
      }
      this.bhTypeValue = val
    },
    sizeChange(value) {
      this.tableParam.pageSize = value;
      this.gettableData();
    },
  },
};
</script>

<style lang="scss" scoped>
.dialog-title {
  font-size: 16px;
  font-weight: bold;
  padding-right: 40px;
}
.el-input,
.el-select {
  width: 240px;
}
.table_link {
  margin: 0 10px;
  color: $bg_color;
}

.table_link:hover {
  opacity: 0.8;
}
</style>
